<?php

namespace App\Http\Controllers\App;

use App\Http\Controllers\Controller;
use App\Models\Cart;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CartController extends Controller
{
    public function all(Request $request)
    {
        $user = getUser($request);
        $carts = Cart::where('user_id', $user['id'])->paginate(10);
        return [
            'result' => 'success',
            'data' => $carts
        ];
    }
    public function create(Request $request)
    {
        $user = getUser($request);
        $productId = $request->get('product_id');
        $product = Product::findOrFail($productId);
        $cart = Cart::where('user_id', $user['id'])->where('product_id', $product['id'])->first();
        if (empty($cart)) {
            $cart = new Cart();
            $cart['quantity'] = 1;
        } else {
            $cart['quantity'] += 1;
        }
        $cart['user_id'] = $user['id'];
        $cart['product_id'] = $product['id'];
        $cart['checked'] = 1;
        switch ($product['activity_type']) {
            case 1: {
                // 普通商品
                $cart['price'] = $product['price'];
                break;
            }
            case 2: {
                // 团购商品
                // 团购商品不能加入购物车
                return [
                    'result' => 'failed',
                    'message' => '团购商品不能加入购物车'
                ];
            }
            case 3: {
                // 秒杀商品
                // 秒杀商品加入购物车的价格是秒杀价
                $cart['price'] = $product['activity']['show_price'];
                break;
            }
            default: break;
        }
        $cart->save();
        return [
            'result' => 'success',
            'data' => $cart
        ];
    }

    public function update(Request $request)
    {
        $id = $request->get('id');
        $cart = Cart::findOrFail($id);
        $type = $request->get('type');
        switch ($type) {
            case 1: {
                $cart['checked'] = !$cart['checked'];
                break;
            }
            case 2: {
                $cart['quantity'] += 1;
                $number = $request->get('number');
                if (!is_int($number) || $number < 1) {
                    return [
                        'result' => 'failed',
                        'message' => '数量有误'
                    ];
                }
                $cart['quantity'] = $number;
                break;
            }
        }
        $cart->save();
        return [
            'result' => 'success',
            'data' => $cart
        ];
    }

    public function destroy(Request $request)
    {
        $id = $request->get('id');
        Log::info($id);
        Cart::destroy($id);
        return [
            'result' => 'success',
            'data' => []
        ];
    }
}
